const app = getApp();
var currentUuid;
var url = app.data.url;
var picRoot = app.data.picRoot;
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    merchantName: '',
    avatarUrl: "",
    merchantId: '',
    active: 'N',
    merchantActive: 'N',
    examineStatus: '',
    showRadio: true,
    loginType: 0,
    totalPrice: 0,
    totalNum: 0,
    uuid: '',
    day: '',
    isCheckActive: false,
    queryType: '',
    userType: '',
    sActive: 5,
    steps: [{
        text: '第一步',
        desc: '点击登录'
      },
      {
        text: '第二步',
        desc: '登录后, 请点击商家信息进行相关资料填写, 并提交审核, 等待后台工作人员审核。'
      },
      {
        text: '第三步',
        desc: '若审核通过, 账号会获得一个月免费试用期, 试用期内商家可对商店进行上下架等操作, 若审核不通过, 请商家按审核信息进行资料修改'
      },
      {
        text: '提示',
        desc: '商家可关注公众号【小指令】, 以便接受系统消息!'
      }
    ],
    overLayShow: false,
    url:''
  },
  /***
   * 退出登录
   */
  logout: function (options) {
    // 清空缓存信息
    Dialog.confirm({
      title: '提示',
      message: '是否退出登录?'
    }).then(() => {
      wx.clearStorage();
      let _that = this;
      _that.setData({
        loginType: 0,
        avatarUrl: "https://img.yzcdn.cn/vant/cat.jpeg"
      })
    }).catch(() => {
      // on cancel
    });

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {



  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _that = this;
    let merchantId = _that.data.merchantId
    if (!merchantId) {
      wx.getStorage({
        key: "merchantId",
        success(res) {
          //console.log(res.data);
          merchantId = res.data;
          _that.loadMoneyAndOrder(merchantId);
        }
      })
    } else {
      _that.loadMoneyAndOrder(merchantId);
    }

    wx.getStorage({
      key: "examineTimes",
      success(res) {
        if (res.data == 0) {
          _that.setData({
            showRadio: false
          })
        }
      }
    })

  },
  previewImg: function (e) {
    let imgUrl = e.currentTarget.dataset.image;
    let _that = this //图片预览
    let envPic = _that.data.envPic;
    wx.previewImage({
      current: imgUrl, // 当前显示图片的http链接
      urls: [imgUrl] // 需要预览的图片http链接列表
    })
  },
  /**
   * 登录
   */
  agreeGetUser: function (options) {
    let _that = this;
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: url + '/WeChatLoginSystemApi/login',
            data: {
              code: res.code
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res.data.data);
              if (res.data.code == 200 ) {
                let item = res.data.data;
                let uuid = item.uuid;
                currentUuid = item.uuid;
                _that.refreshMerhcant(uuid);
                console.log(picRoot + item.img);
                wx.setStorage({
                  key: "uuid",
                  data: item.uuid
                })
                _that.setData({
                  avatarUrl: picRoot + item.img,
                  merchantId: item.merchantId,
                  merchantName: item.merchantName,
                  loginType: 1,
                  active: item.active,
                  examineStatus: item.examineStatus,
                  userType: item.userType,
                  url:'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxab642c2d7c8e9f19&redirect_uri=https://www.xxcamanage.cn/WeChatAuthApi/getServiceOpenIdForMerchant&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirec'
                })

                if (item.examineTimes == 0) {
                  _that.setData({
                    showRadio: false
                  })
                }
                wx.setStorage({
                  key: "active",
                  data: item.active
                })
                wx.setStorage({
                  key: "userTag",
                  data: item.userType
                })
                wx.setStorage({
                  key: "examineStatus",
                  data: item.examineStatus
                })
                wx.setStorage({
                  key: "examineTimes",
                  data: item.examineTimes
                })
                wx.setStorage({
                  key: "uuid",
                  data: uuid
                })
                wx.setStorage({
                  key: "avatarUrl",
                  data: picRoot + item.img
                })
                wx.setStorage({
                  key: "merchantName",
                  data: item.merchantName
                })
                wx.setStorage({
                  key: "merchantId",
                  data: item.merchantId
                })
                wx.setStorage({
                  key: "loginType",
                  data: 1
                })
                wx.showToast({
                  title: "登录成功!",
                  icon: "success",
                  duration: 2000
                })
                _that.loadMoneyAndOrder(item.merchantId);
              } else if (res.data.code == 0){
                _that.setData({
                  loginType: 1,
                  merchantName: '请先关注册公众号, 并注册成商家。'
                })
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              } else {
                console.log("登录失败!");
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              }
            },
            fail: function (res) {
              console.info('登录失败');
            },
            complete: function (res) {
              console.info('登录请求完成');
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }

      }
    })
  },

  /**
   * 跳转页面
   */
  toPageIndex: function (options) {
    let _that = this;
    let pageId = options.currentTarget.dataset.pageid;
    let merchantId = _that.data.merchantId;
    let isCheckActive = _that.data.isCheckActive;
    let userType = _that.data.userType;
    let url = '';
    if (pageId == 1) {
      // 订单管理
      url = '../../pages/order-manage/index?merchantId=' + merchantId;
    } else if (pageId == 2) {
      // 历史订单
      url = '../../pages/order-history/index?merchantId=' + merchantId;
    } else if (pageId == 3) {
      // 退订管理
      url = '../../pages/order-refund/index?merchantId=' + merchantId;
    } else if (pageId == 4) {
      // 商品管理
      url = '../../pages/detail/index?merchantId=' + merchantId;
    } else if (pageId == 5) {
      // 商家管理
      url = '../../pages/merchant/index?merchantId=' + merchantId + '&isCheckActive=' + isCheckActive;
    } else if (pageId == 6) {
      // 系统充值
      url = '../../pages/pay/index?merchantId=' + merchantId;
    } else if (pageId == 7) {
      // 酒店管理
      url = '../../pages/hotel/index?merchantId=' + merchantId;
    } else if (pageId == 8) {
      // 景点管理
      url = '../../pages/scenic/index?merchantId=' + merchantId;
    } else if (pageId == 9) {
      // 车服管理
      url = '../../pages/car/index?merchantId=' + merchantId;
    } else if (pageId == 10) {
      // 油站管理
      url = '../../pages/oil/index?merchantId=' + merchantId;
    } else if (pageId == 11) {
      // 餐桌管理
      url = '../../pages/desk/index?merchantId=' + merchantId;
    } else if (pageId == 12) {
      // 服务管理
      url = '../../pages/service/index?merchantId=' + merchantId;
    } else if (pageId == 13) {
      // 配送时间管理
      url = '../../pages/take-out-time/index?merchantId=' + merchantId;
    } else if (pageId == 14) {
      // 超市管理
      url = '../../pages/market/index?merchantId=' + merchantId;
    } else if (pageId == 15) {
      // 特产管理
      url = '../../pages/specialty/index?merchantId=' + merchantId;
    } else if (pageId == 16) {
      // 医疗保健
      url = '../../pages/treatment/index?merchantId=' + merchantId;
    } else if (pageId == 17) {
      // 娱乐
      url = '../../pages/recreation/index?merchantId=' + merchantId;
    } else if (pageId == 18) {
      // 美容美发
      url = '../../pages/hairdressing/index?merchantId=' + merchantId;
    } else if (pageId == 19) {
      // 起送金额
      url = '../../pages/send-prise/index?merchantId=' + merchantId;
    } else if (pageId == 20) {
      // 起送金额
      url = '../../pages/clothes/index?merchantId=' + merchantId;
    }
    wx.navigateTo({
      url: url,
    })
  },
  /**
   * 跳转我的店铺
   */
  toMyShop: function (options) {
    let _that = this;
    let merchantId = _that.data.merchantId;
    let queryType = _that.data.queryType;
    let loginType = _that.data.loginType;
    let userType = _that.data.userType;
    if (loginType == 0) {
      wx.showToast({
        title: '请先登录!',
        icon: "none",
        duration: 2000
      })
      return;
    }
    if (userType == -1) {
      wx.showToast({
        title: '您当前未通过审核!',
        icon: "none",
        duration: 2000
      })
      return;
    }
    let url = '';
    if (queryType == 0) {
      // 餐饮
      url = '../../pages/show-shop/index?merchantId=' + merchantId
    } else if (queryType == 1) {
      // 酒店
      url = '../../pages/show-hotel/index?merchantId=' + merchantId 
    } else if (queryType == 2) {
      // 景点
      url = '../../pages/show-scenic/index?merchantId=' + merchantId + "&descType=13"
    } else if (queryType == 3) {
      // 车服
      url = '../../pages/show-car/index?merchantId=' + merchantId  + "&descType=14"
    } else if (queryType == 4) {
      // 加油
      url = '../../pages/show-oil/index?merchantId=' + merchantId  + "&descType=15"
    } else if (queryType == 5) {
      // 特产
      url = '../../pages/show-specialty/index?merchantId=' + merchantId  + "&descType=17"
    } else if (queryType == 6) {
      // 超市
      url = '../../pages/show-market/index?merchantId=' + merchantId  + "&descType=16"
    } else if (queryType == 9) {
      // 美容美发
      url = '../../pages/show-hairdressing/index?merchantId=' + merchantId  + "&descType=20"
    } else if (queryType == 7) {
      // 医疗保健
      url = '../../pages/show-treatment/index?merchantId=' + merchantId  + "&descType=18"
    } else if (queryType == 8) {
      // 娱乐
      url = '../../pages/show-recreation/index?merchantId=' + merchantId  + "&descType=19"
    } else if (queryType == 10) {
      // 名牌服饰
      url = '../../pages/show-clothes/index?merchantId=' + merchantId  + "&descType=21"
    }
    wx.navigateTo({
      url: url
    })


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _that = this;
    wx.getStorage({
      key: "uuid",
      success(res) {
        console.log(res.data);
        if (res.data) {
          _that.refreshMerhcant(res.data);
        }
        currentUuid = res.data;
      }
    })

  },

  /**
   * 刷新商家信息
   */
  refreshMerhcant: function (uuid) {
    let _that = this;
    wx.request({
      url: url + '/MerchantPaySystemApi/queryMerchant',
      data: {
        uuid: uuid
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {
          let item = res.data.data;
          console.log("onShow:");
          console.log(item);
          _that.setData({
            active: item.active,
            examineStatus: item.examineStatus,
            day: item.day,
            isCheckActive: item.isCheckActive,
            queryType: item.type,
            merchantActive: item.merchantActive == "Y" ? true : false
          })
          _that.loadData();
          wx.setStorage({
            key: "queryType",
            data: item.type
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 3000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let _that = this;
    let merchantId = _that.data.merchantId;
    _that.loadMoneyAndOrder(merchantId);
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  onActiveChange: function ({
    detail
  }) {
    let _that = this;
    let isCheckActive = _that.data.isCheckActive;
    if (!isCheckActive) {
      Dialog.alert({
        message: ' 您已过了免费试用期或使用有效期,请前往充值'
      }).then(() => {
        // on close
      });
    } else {
      console.log(detail);

      _that.setData({
        overLayShow: true
      });
      //请求更新
      console.info("用户uuid:" + currentUuid);

      wx.request({
        url: url + '/MerchantApi/activate',
        data: {
          uuid: currentUuid,
          active: detail ? "Y" : "N"
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          if (res.data.code == 200) {
            _that.setData({
              overLayShow: false,
              merchantActive: detail
            });
          } else {
            _that.setData({
              overLayShow: false
            });
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 3000
            })
          }
        },
        fail: function (res) {
          console.info('submit fail');
        },
        complete: function (res) {
          console.info('submit complete');
        }
      })



    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 加载金额, 有效订单
   */
  loadMoneyAndOrder: function (merchantId) {
    let _that = this;

    wx.request({
      url: url + '/OrderSystemApi/queryMerchantOrderParam',
      data: {
        merchantId: merchantId
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        _that.setData({
          totalPrice: res.data.data.totalPrice,
          totalNum: res.data.data.orderNum
        })
        wx.setStorage({
          key: "examineTimes",
          data: res.data.data.examineTimes
        })
        if (res.data.data.examineTimes > 0) {
          _that.setData({
            showRadio: true
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },
  /**
   * 打开页面执行
   */
  loadData: function () {
    let _that = this;
    wx.getStorage({
      key: "userTag",
      success(res) {
        console.log("[userTag]");
        console.log(res);
        console.log(res.data);
        _that.setData({
          userType: res.data
        })
      }
    })

    wx.getStorage({
      key: "loginType",
      success(res) {
        console.log("[loginType]");
        console.log(res);
        _that.setData({
          loginType: res.data
        })
      }
    })
    wx.getStorage({
      key: "queryType",
      success(res) {
        console.log("[queryType]");
        console.log(res);
        _that.setData({
          queryType: res.data
        })
      }
    })

    wx.getStorage({
      key: "avatarUrl",
      success(res) {
        console.log("[avatarUrl]");
        console.log(res);
        _that.setData({
          avatarUrl: res.data
        })
      }
    })

    wx.getStorage({
      key: "merchantId",
      success(res) {
        console.log("[merchantId]");
        console.log(res);
        _that.setData({
          merchantId: res.data
        })
      }
    })

    wx.getStorage({
      key: "merchantName",
      success(res) {
        console.log("[merchantName]");
        console.log(res);
        _that.setData({
          merchantName: res.data
        })
      }
    })
  }
})